﻿using BlazorAdmin.Tcp.Server;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;

namespace Pangeo.Admin.Tasks.Jobs
{
    public class SyncClientDeviceInfo
    {
        private readonly TcpServer<DeviceTcpToken>? tcpServer;
        private static readonly JsonSerializerSettings jsonSettings = new() { NullValueHandling = NullValueHandling.Ignore };

        public SyncClientDeviceInfo(IServiceScopeFactory _scopeFactory)
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                tcpServer = scope.ServiceProvider.GetRequiredService<TcpServer<DeviceTcpToken>>();
            }
        }

        public void Run()
        {
            tcpServer?.Connections.ToList().ForEach(conn =>
            {
                tcpServer?.Send(JsonConvert.SerializeObject(new
                {
                    IsBackup = true
                }, jsonSettings), conn);

                Task.Delay(500); // 每下发一个延迟1秒
            });
        }
    }
}
